解决a标签download不生效,只跳转新标签页需手动另存为

您所在的位置:网站首页 html a标签跳转 解决a标签download不生效,只跳转新标签页需手动另存为

解决a标签download不生效,只跳转新标签页需手动另存为

2023-03-30 20:00| 来源: 网络整理| 查看: 265

后端为URL时候:把server给的文件URL通过fetch转换为blob类型:变成blob:xxx

let url = "https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fimg.jj20.com%2Fup%2Fallimg%2F4k%2Fs%2F02%2F2109242332225H9-0-lp.jpg&refer=http%3A%2F%2Fimg.jj20.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=auto?sec=1650945561&t=c9a7a0e4614f9d0b5510dd512aebfe27"; fetch(url) .then((response) => response.blob()) .then((res) => { let blob = new Blob([res]); // 通过URL.createObjectURL生成文件路径 let url = window.URL.createObjectURL(blob); // 创建a标签 let ele = document.createElement("a"); ele.style.display = "none"; // 设置href属性为文件路径,download属性可以设置文件名称 ele.href = url; ele.download = "a标签dow不触发下载-单跳新页面.jpg"; // 将a标签添加到页面并模拟点击 document.querySelectorAll("body")[0].appendChild(ele); ele.click(); // 移除a标签 ele.remove(); });

响应头定义为responseType: "arraybuffer",前端自己拼接变成blob类型:变成blob:xxx

//下载云端文件 downloadFile(fileName) { this.isDownLoadProgress = true; axios({ method: "get", url: `${process.env.VUE_APP_BASEURL}/downloadFile?roomName=${this.roomName}&fileName=${fileName}&role=教师`, responseType: "arraybuffer", // arraybuffer是js中提供处理二进制的接口 onDownloadProgress: (progressEvent) => { if (progressEvent.lengthComputable) { var complete = ((progressEvent.loaded / progressEvent.total) * 100) | 0; this.downLoadValue = complete; if (complete >= 100) { this.isDownLoadProgress = false; this.downLoadValue = 0; // 重新置0 this.$buefy.toast.open({ duration: 2000, type: "is-success", message: "下载成功!", }); } } }, }).then((res) => { // 用返回二进制数据创建一个Blob实例 if (!res) return; let blob = new Blob([res.data]); // for .xlsx files // 通过URL.createObjectURL生成文件路径 let url = window.URL.createObjectURL(blob); // 创建a标签 let ele = document.createElement("a"); ele.style.display = "none"; // 设置href属性为文件路径,download属性可以设置文件名称 ele.href = url; ele.download = fileName; // 将a标签添加到页面并模拟点击 document.querySelectorAll("body")[0].appendChild(ele); ele.click(); // 移除a标签 ele.remove(); }); },

 



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3